package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * sky-take-out
 * com.sky.task
 * OrderTask <br>
 * 订单定时任务处理类
 *
 * @author Ablecisi
 * @version 1.0
 * {@code 2025/5/24 星期六 14:40}
 */

@Component
@Slf4j
public class OrderTask {
    private final OrderMapper orderMapper;

    @Autowired
    public OrderTask(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    /**
     * 订单支付超时处理定时任务
     * 每分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder() {
        // 订单处理逻辑
        log.info("订单支付超时处理定时任务执行中... {}", LocalDateTime.now());

        // select * from orders where pay_status = ? and order_time < (当前时间 - 15分钟)
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));

        if (ordersList != null && !ordersList.isEmpty()) {
            ordersList.forEach((order) -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时未支付，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }

    /**
     * 订单配送超时处理定时任务
     * 每天凌晨2点执行
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void processDeliveryOrder() {
        // 订单配送逻辑
        log.info("订单配送超时处理定时任务执行中... {}", LocalDateTime.now());

        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusHours(-2));

        if (ordersList != null && !ordersList.isEmpty()) {
            ordersList.forEach((order) -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
